
package com.anttek.explorer.pdfviewerplugin;

import com.anttek.common.utils.Intents;
import com.anttek.explorer.pdfviewerplugin.R.raw;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

/**
 * http://stackoverflow.com/questions/5301054/android-reading-from-
 * datainputstream-works-in-emulator-but-not-on-device/8383864#8383864
 * 
 * @author Administrator
 */
public class TiffViewerPluginActivity extends Activity implements OnClickListener {
    private String DEST_FILE = "libvudroid.so";
    private String SRC_FILE = "libvudroid.so";
    private static final String TYPE = "pdf";

    private ProgressDialog dialog;
    private File fsdcard;
    public static final String ACTION = "com.anttek.intent.action.INSTALL_EXPLORER_PLUGINS";
    public static final String EXTRA_FILE = "f";
    public static final String EXTRA_NAME = "n";
    private static final String EXTRA_TYPE = "t";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.button_install).setOnClickListener(this);
        findViewById(R.id.button_download_ex).setOnClickListener(this);
    }

    @Override
    public void onClick(View arg0) {
        int id = arg0.getId();
        if (id == R.id.button_install) {
            install();
        } else if (id == R.id.button_download_ex) {
            download("com.anttek.explorer");
        }
    }

    private void download(String pkg) {
        Intents.startMarketAppActivity(this, pkg);
    }

    private void install() {

        String targetPackages[] = new String[] {
                "com.anttek.explorer",
        };

        if (!existsTargetPackage(targetPackages)) {
            Toast.makeText(
                    this,
                    "AntTek Explorer does not install yet. Please install it first (click button below).",
                    Toast.LENGTH_LONG).show();
            return;
        }

        dialog = new ProgressDialog(this);
        dialog.setMessage("Installing, please wait...");
        dialog.show();
        IntentFilter intentFilter = new IntentFilter(
                "com.anttek.intent.action.INSTALL_EXPLORER_PLUGINS_FINISHED");
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                if (fsdcard != null) {
                    fsdcard.delete();
                }
                try {
                    unregisterReceiver(this);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }, intentFilter);

        fsdcard = Environment.getExternalStorageDirectory();
        if (fsdcard != null && fsdcard.isDirectory()) {
            try {
                InputStream from = this.getAssets().open(SRC_FILE);
                File file = new File(fsdcard.getAbsolutePath(), DEST_FILE);
                OutputStream to = new FileOutputStream(file);

                copy(new BufferedInputStream(from, 2048), new BufferedOutputStream(to, 2048));

                Intent data = new Intent(ACTION);
                data.putExtra(EXTRA_FILE, file.getAbsolutePath());
                data.putExtra(EXTRA_NAME, getString(R.string.app_name));
                data.putExtra(EXTRA_TYPE, TYPE);

                sendBroadcast(data);
            } catch (Throwable e) {
                e.printStackTrace();
                Toast.makeText(this, "Fail to install plugin: " + e.getLocalizedMessage(),
                        Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        }
    }

    private boolean existsTargetPackage(String[] targetPackages) {

        PackageManager pm = getPackageManager();

        for (String pkg : targetPackages) {
            try {
                ApplicationInfo info = pm.getApplicationInfo(pkg, 0);

                if (info != null) {
                    return true;
                }
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    public static void copy(InputStream from, OutputStream to)
            throws IOException {
        try {
            byte[] buffer = new byte[2048];
            int bytesRead;

            while ((bytesRead = from.read(buffer)) != -1) {
                to.write(buffer, 0, bytesRead); // write
            }
        } finally {
            if (from != null)
                try {
                    from.close();
                } catch (IOException e) {
                    ;
                }
            if (to != null)
                try {
                    to.flush();
                    to.close();
                } catch (IOException e) {
                    ;
                }
        }
    }

}
